package com.navinfo.opentsp.qingqi.trackoptimize.service;


import com.navinfo.opentsp.qingqi.trackoptimize.entity.MongoTripDataEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 查询服务
 * create by wangshuai 2017-03-17
 */
@Service
public class TrackQueryService{

    protected static final Logger logger = LoggerFactory.getLogger(TrackQueryService.class);

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 多线程查询各周表汇总后返回
     * @param query
     * @param list
     * @return
     */
    public List<MongoTripDataEntity> queryMongo(final Query query, final List<String> list){
        List<MongoTripDataEntity> returnList = new ArrayList<MongoTripDataEntity>();
        if(list == null || list.size() == 0){
            return returnList;
        }
        List<Callable<List<MongoTripDataEntity>>> callables = new ArrayList<>();
        //根据需要查询表个数创建callable
        for (int i=0;i<list.size();i++) {
            final int finalI = i;
            Callable<List<MongoTripDataEntity>> callable;
            callable = new Callable<List<MongoTripDataEntity>>() {
                    public List<MongoTripDataEntity> call() throws Exception {
                        return getResult(query,list.get(finalI));
                    }
                };
            callables.add(callable);
        }

        ExecutorService executor = Executors.newFixedThreadPool(list.size());

        try {
            //执行mongo查询
            List<Future<List<MongoTripDataEntity>>> futures = executor.invokeAll(callables);
            //拼装为一个list
            for(Future<List<MongoTripDataEntity>> future : futures) {
                returnList.addAll(future.get());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }  finally {
            executor.shutdown();
        }

        //进行排序
        Collections.sort(returnList, new Comparator() {
            public int compare(Object a, Object b) {
                long oneStartTime = ((MongoTripDataEntity) a).get_start_time();
                long twoStartTime = ((MongoTripDataEntity) b).get_start_time();
                return (int) (oneStartTime - twoStartTime);
            }
        });
        return returnList;
    }

    private List<MongoTripDataEntity> getResult(Query query, String tn){
        return mongoTemplate.find(query, MongoTripDataEntity.class, tn);
    }
}